<?php


namespace App\Http\Controllers\Saas;


use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Resources\HousePaginationCollection;
use App\Http\Resources\PaginationCollection;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\Country;
use App\Model\House;
use App\Service\Fdd\FddInterface;
use App\Utils\Result;
use Illuminate\Http\Request;

class ContractController extends Controller
{
    protected FddInterface $fdd;

    public function __construct(FddInterface $fdd)
    {
        $this->fdd = $fdd;
    }

    public function index(Request $request)
    {
        // Get the current page number from the request parameters (default to 1)
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);

        $keyword = $request->input('keyword');
        $query = Contract::query();
        $status = $request->input('status');
        if ($status) {
            $query->where('status', $status);
        }
        $user = $this->getUser();
        if($user->roles != 'admin' && !$keyword){
            return Result::success([]);
        }
        if ($keyword) {
            $query->whereHas('house', function($q) use ($keyword) {
                $q->where('estate_name', 'like','%'.$keyword.'%');
            });
        }

        // Get a paginated collection of House models from the database
        $data = $query->with('house', 'masterTenant', 'business')
            ->orderByDesc('id')
            ->whereHas('house')
            ->paginate($perPage, ['*'], 'page', $page);

        return Result::success(new PaginationCollection($data));
    }

    public function tenantList(Request $request){
        $page = $request->input('page', 1);
        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $id = $request->input('id',0);
        $status = $request->input('status');
        $businessName = $request->input('businessName');
        if(!$id){
            return Result::error(1001,'缺失参数id');
        }
        $country = Country::query()->where('id',$id)->first();
        if(!$country){
            return Result::error(1001,'参数id模型不存在');
        }
        $query = House::query();
        if ($businessName) {
            $query->whereHas('business', function($q) use ($businessName) {
                $q->where('name', $businessName);
            })->orWhereHas('business.user', function($q) use ($businessName) {
                $q->where('mobile', $businessName);
            });
        }
        if ($status == 'hired') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
            });
        }
        if ($status == 'vacant') {
            $query->whereDoesntHave('contract', function($q) {
                $q->where('status', '<=', ContractStatus::YIQIANYUE);
            });
        }
        if ($status == 'expire') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
                $q->where('expired_at', '<', now()->addDays(30)->toDateString());
            });
        }
        if ($status == 'fast') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::FASTQY);
            });
        }

        if ($status == 'expired') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
                $q->where('expired_at', '<', now()->toDateString());
            });
        }
        if ($status == 'fail') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
                $q->whereHas('bills', function($q) {
                    $q->where('is_paid', 0)->where('is_close', 0)->where('pay_date', '<', now()->toDateString());
                });
            });
        }
        if ($status == 'signing') {
            $query->whereHas('contract', function($q) {
                $q->whereIn('status', [ContractStatus::QIANDINGZHONG, ContractStatus::DAIQIANYUE]);
            });
        }
        if($country->province){
            $query->where('province',$country->province);
        }
        if($country->city){
            $query->where('city',$country->city);
        }
        if($country->district){
            $query->where('district',$country->district);
        }
        if($country->name){
            $query->where('estate_name','like','%'.$country->name.'%');
        }
        $houses = $query->with('contract', 'contract.contractTenant', 'device', 'business', 'business.user')
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new HousePaginationCollection($houses));
    }

    public function getTenant(Request $request,$id){
        $data['items'] = ContractTenant::query()->where('contract_id',$id)->get();
        ContractTenant::query()->where('contract_id',$id)->update(['is_read'=>2]);
        $data['count'] = ContractTenant::query()->where('contract_id',$id)->count();
        return Result::success($data);
    }

    public function getSignTaskDownloadUrl(Request $request, $id)
    {
        $contract = Contract::query()->with('business', 'business.user', 'business.user.fdd')->find($id);
        $fdd = $contract->business->user->fdd;
        // 获取签署链接
        $result = $this->fdd->signTaskGetDownloadUrl([
            'ownerId' => [
                'idType' => $fdd->is_corp ? 'corp' : 'person',
                'openId' => $fdd->open_user_id,
            ],
            'signTaskId' => $contract->sign_task_id,
        ]);

        return Result::success($result);
    }
}
